import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import postCssPxToRem from "postcss-pxtorem";
import path from "path";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "unplugin-vue-components/resolvers";
import { viteMockServe } from "vite-plugin-mock";

export default ({ mode }) => {
  const env = loadEnv(mode, "./env");
  const port = parseInt(env.VITE_APP_PORT, 10) || 3000;

  return defineConfig({
    // 开发、部署时挂在根域名下的前缀
    base: "/jznota/",

    envDir: "env",

    plugins: [
      vue(),
      Components({
        resolvers: [VantResolver()],
      }),
      viteMockServe({
        mockPath: "mock",
        localEnabled: true,
        supportTs: false,
      }),
    ],

    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },

    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 37.5,
            propList: ["*"],
          }),
        ],
      },
    },

    build: {
      // 确保生成 source maps
      sourcemap: true,
    },

    server: {
      host: "0.0.0.0",
      port: port,
      proxy: {
        "/api": {
          target: "http://localhost:8080",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
  });
};
